<template>
  <div class="home">
    <van-nav-bar title="老人伴侣" left-arrow @click-left="onClickLeft" />
    <div class="home-content">
      <p class="home-content-area-text">基本信息</p>
      <transition-group tag="ul" class="home-content-info">
        <li
          class="home-content-info-item"
          @click="onDevices(item, index)"
          v-for="(item, index) in infoData"
          :key="item"
        >
          <div class="home-content-info-item-title">
            <p class="home-content-info-item-title-name">{{ item.name }}</p>
          </div>
          <p class="home-content-info-item-data">{{ item.data }}</p>
        </li>
      </transition-group>
      <p class="home-content-area-text">历史数据</p>
      <div class="home-content-echarts">
        <div
          id="echartbeat"
          style="margin: 10px; width: auto; height: 30vh"
        ></div>
      </div>
      <div class="home-content-echarts">
        <div
          id="echarttemp"
          style="margin: 10px; width: auto; height: 30vh"
        ></div>
      </div>
    </div>
  </div>
</template>

<script>
import mqtt from "mqtt";
import * as echarts from "echarts";
//import { Toast } from 'vant';
var client;
const options = {
  connectTimeout: 40000,
  clean: true,
};
client = mqtt.connect("ws://121.5.58.100:8083/mqtt", options);

export default {
  components: {},
  created: function () {
    this.mqttMsg();
  },
  mounted: function () {
    //this.myEcharts();
    this.myEcharts();
    console.log("echarts");
  },
  data: function () {
    return {
      echarts: require("echarts"),
      myChart: "",
      beatdata: [],
      beatdate:[],
      tempdata: [],
      tempdate:[],
      infoData: [
        {
          // Icon: require('@img/ADD1.svg'),
          name: "当前心率",
          data: "--",
        },
        {
          // Icon: require('@img/ADD1.svg'),
          name: "皮肤温度",
          data: "--",
        },
      ],
    };
  },
  methods: {
    onClickLeft() {
      this.$router.go(-1);
    },
    formatDate(params) {
      let date = params;
      let formatStr = "HH:mm:ss";
      // 传入日期字符串 - 转成时间戳 - 转成标准时间
      let timeStamp = params.getTime();
      console.log(timeStamp);
      date = new Date(timeStamp);
      formatStr = formatStr.replace(
        new RegExp("yyyy"),
        `${date.getFullYear()}`
      );
      const month = date.getMonth() + 1;
      formatStr = formatStr.replace(
        new RegExp("MM"),
        `${month > 9 ? month : "0" + month}`
      );
      const day = date.getDate();
      formatStr = formatStr.replace(
        new RegExp("dd"),
        `${day > 9 ? day : "0" + day}`
      );
      const hour = date.getHours();
      formatStr = formatStr.replace(
        new RegExp("HH"),
        `${hour > 9 ? hour : "0" + hour}`
      );
      const min = date.getMinutes();
      formatStr = formatStr.replace(
        new RegExp("mm"),
        `${min > 9 ? min : "0" + min}`
      );
      const sec = date.getSeconds();
      formatStr = formatStr.replace(
        new RegExp("ss"),
        `${sec > 9 ? sec : "0" + sec}`
      );
      return formatStr;
    },
    myEcharts() {

      // 基于准备好的dom，初始化echarts实例
      this.beatChart = echarts.init(document.getElementById("echartbeat"));
      this.tempChart = echarts.init(document.getElementById("echarttemp"));
      // 绘制图表
      //console.log(data);
      this.beatChart.setOption({
        tooltip: {
          trigger: "axis",
          position: function (pt) {
            return [pt[0], "10%"];
          },
        },
        title: {
          left: "center",
          text: "心率测量记录",
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: this.beatdate,
        },
        yAxis: {
          type: "value",
          boundaryGap: [0, "100%"],
          min: 0,
          max: 150,
        },
        series: [
          {
            name: "心率数据",
            type: "line",
            symbol: "none",
            sampling: "lttb",
            itemStyle: {
              color: "rgb(255, 70, 131)",
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: "rgb(255, 158, 68)",
                },
                {
                  offset: 1,
                  color: "rgb(255, 70, 131)",
                },
              ]),
            },
            data: this.beatdata,
          },
        ],
      });
      this.tempChart.setOption({
        tooltip: {
          trigger: "axis",
          position: function (pt) {
            return [pt[0], "10%"];
          },
        },
        title: {
          left: "center",
          text: "体温测量记录",
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: this.tempdate,
        },
        yAxis: {
          type: "value",
          boundaryGap: [0, "100%"],
          min: 30,
          max: 45,
        },
        series: [
          {
            name: "体温",
            type: "line",
            symbol: "none",
            sampling: "lttb",
            itemStyle: {
              color: "rgb(255, 70, 131)",
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: "rgb(255, 158, 68)",
                },
                {
                  offset: 1,
                  color: "rgb(255, 70, 131)",
                },
              ]),
            },
            data: this.tempdata,
          },
        ],
      });
    },
    mqttMsg() {
      client.on("connect", () => {
        console.log("连接成功！！！");
        client.subscribe("LRBL/info", { qos: 0 }, (error) => {
          if (!error) {
            console.log("订阅成功");
          } else {
            console.log("订阅失败");
          }
        });
      });
      // 接收消息处理
      client.on("message", (topic, message) => {
        console.log(message.toString()); //控制台显示接收到的数据
        this.res = JSON.parse(message.toString());
        this.infoData[0].data = this.res.BE + "b/Min";
        this.infoData[1].data = this.res.TC.toFixed(2) + "°C";
        if(this.res.BE!==0){
          this.beatdate.push(this.formatDate(new Date()))
          this.beatdata.push(this.res.BE);
        }
        if(this.res.TC>30){
          this.tempdate.push(this.formatDate(new Date()))
          this.tempdata.push(this.res.TC);
        }
        this.beatChart.setOption({
          xAxis: {
          data: this.beatdate,
        },
              series: [{
                  data: this.beatdata
              }]
          });

        this.tempChart.setOption({
            xAxis: {
            data: this.tempdate,
          },
                series: [{
                    data: this.tempdata
                }]
            });
        });
    },
    onDevices: function (item, index) {
      if (index === 5) {
        this.sendLed = this.res.led === 0 ? "ledOn" : "ledOff";
        this.send =
          '{"code":"' +
          this.sendLed +
          '","temp": "' +
          this.res.temp +
          '","ip": "' +
          this.res.ip +
          '", "rain": "' +
          this.res.rain +
          '", "hum": "' +
          this.res.hum +
          '", "LED": "' +
          this.res.temp +
          '", "fire": "' +
          this.res.fire +
          '","gas": "' +
          this.res.gas +
          '",  "led": "' +
          this.res.led +
          '"}';
        client.publish("House", this.send);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.v-enter,
.v-leave-to {
  opacity: 0;
  transform: translateX(100px);
}

.v-enter-active,
.v-leave-to {
  transition: all 0.6s ease;
}

/* v-move 和 v-leave-to 配合使用，能够实现列表后续的元素，逐渐飘上来的效果 */
.v-move {
  transition: all 0.6s ease;
}

.v-leave-to {
  position: absolute;
}
.home {
  width: 100%;
  height: 100%;
  overflow: auto;
  display: flex;
  flex-flow: column;
  position: absolute;
  &-content {
    height: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    align-items: left;
    justify-content: left;
    transition: 0.3s;
    overflow-x: hidden;
    &-echarts {
      transition: 0.5s;
      text-align: center;
      margin: 0 16px 15px;
      //padding: 0 16px 15px;
      border-radius: 20px 20px 20px 20px;
      // box-shadow: 0 0 16px 0 rgba(0, 0, 0, 0.3);
      width: auto;
      height: 40vh;
      display: flex;
      position: relative;
      flex-direction: column;
      justify-content: left;
      background-color: rgba(255, 255, 255, 0.9);
      background-attachment: fixed;
    }
    &-control {
      border-radius: 20px;
      margin-top: 0px;
      margin-left: 20px;
      margin-right: 20px;
      margin-bottom: 20px;
    }
    &-area {
      &-text {
        margin-left: 20px;
        font-size: 5vw;
        color: white;
        font-weight: 900;
      }
    }
    &-text {
      margin: px2rem(20);
      font-size: px2rem(30);
      color: white;
      font-weight: 600;
      margin-bottom: px2rem(30);
    }
    &-shebei {
      margin-left: px2rem(20);
      margin-bottom: px2rem(5);
      font-size: px2rem(14);
      color: white;
      font-weight: 400;
    }
    &-info {
      transition: 0.5s;
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      padding: 0 16px 15px;

      &-item {
        transition: 0.5s;
        margin: 5px;
        text-align: center;
        padding: 5px;
        border-radius: 20px 20px 20px 20px;
        // box-shadow: 0 0 16px 0 rgba(0, 0, 0, 0.3);
        width: calc(50% - 20px);
        // height: calc(50% - 10px);
        display: flex;
        position: relative;
        flex-direction: column;
        justify-content: left;
        background-color: rgba(255, 255, 255, 0.9);
        background-attachment: fixed;
        &-title {
          display: flex;
          flex-direction: row;
          align-items: center;

          &-name {
            margin: auto;
            transition: 0.5s;
            text-align: left;
            color: black;
            //margin-top: 0;
            font-size: 4vw;
          }
        }

        &-data {
          transition: 0.5s;
          // text-align: right;
          color: black;
          margin: auto;
          font-size: 9vw;
          font-weight: 500;
        }
      }
    }
  }
}
.custom-button {
  width: auto;
  padding: 5px 10px;
  color: #fff;
  font-size: 4vw;
  line-height: 5vw;
  text-align: center;
  background-color: #0aadee;
  border-radius: 20px;
}
</style>
